<template>
  <div class="test-manage">
    <div class="page-header">
      <h1>测试管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建测试
      </el-button>
    </div>

    <!-- 测试列表 -->
    <el-card>
      <el-table :data="tests" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="test" label="测试内容" min-width="200" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingTest ? '编辑测试' : '创建测试'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="内容" prop="test">
          <el-input
            v-model="form.test"
            type="textarea"
            :rows="4"
            placeholder="请输入测试内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import * as testApi from '@/api/test'
import { Plus } from '@element-plus/icons-vue'
import type { Test, TestCreateRequest, TestUpdateRequest } from '@/types/api'

const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const editingTest = ref<Test | null>(null)
const formRef = ref<FormInstance>()

const tests = ref<Test[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 表单数据
const form = reactive<TestCreateRequest>({
  test: ''
})

// 表单验证规则
const rules: FormRules = {
  test: [
    { required: true, message: '请输入测试内容', trigger: 'blur' },
    { max: 500, message: '内容长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 获取测试列表
const fetchTests = async () => {
  try {
    loading.value = true
    const data = await testApi.getTests({
      page: currentPage.value,
      page_size: pageSize.value
    })
    tests.value = data
    console.log(data)
  } catch (error) {
    console.error('获取测试列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 编辑测试
const handleEdit = (test: Test) => {
  editingTest.value = test
  form.test = test.test
  showCreateDialog.value = true
}

// 删除测试
const handleDelete = async (test: Test) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条测试记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await testApi.deleteTest(test.id)
    ElMessage.success('删除成功')
    fetchTests()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除测试失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (editingTest.value) {
      await testApi.updateTest(editingTest.value.id, form as TestUpdateRequest)
      ElMessage.success('更新成功')
    } else {
      await testApi.createTest(form)
      ElMessage.success('创建成功')
    }
    
    handleCancel()
    fetchTests()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  showCreateDialog.value = false
  editingTest.value = null
  form.test = ''
  formRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchTests()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchTests()
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchTests()
})
</script>

<style lang="scss" scoped>
.test-manage {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      margin: 0;
      color: var(--text-primary);
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
